package map.android.baidu.carpool.utils;

import java.io.Serializable;
import java.util.Calendar;

import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.animation.AnimationListenerForCarpool;
import map.android.baidu.carpool.animation.AnimationUtilsForCarpool;
import map.android.baidu.carpool.data.impl.OrderCancelData;
import map.android.baidu.carpool.data.impl.OrderDetailData;
import map.android.baidu.carpool.page.home.OrderDetailPage;
import map.android.baidu.carpool.response.OrderCancelResponse;
import map.android.baidu.carpool.response.OrderDetailResponse;

/**
 * @Author chenlei18
 * @Description 拼车发单界面
 * @CreateTime 2015-3-28 下午5:20:10
 */
public class CarPoolReceiptDialog extends Dialog implements OnClickListener, Serializable {

    private static final long serialVersionUID = 4601519215291859581L;
    private View mView;
    private View mCloseDialog;
    private View mCancelOrder;
    /**
     * 通知司机的时间*
     */
    private TextView mNotifyTimeTv;
    /**
     * 通知司机的时间单位*
     */
    private TextView mNotifyTimeUnitTv;
    /**
     * 通知司机的个数*
     */
    private TextView mReceiptNumTv;

    private Context mContext = null;
    private int mPushNumber = 0;
    private int mShowNumber = 0;
    private long mWaitDisableTime = 0L;
    private long mCurrentSystem = 0L;
    private long mWaitEndTime = 0L;
    private long mCountDownTime = 0L;
    private Calendar mCalendarShow = Calendar.getInstance();
    private String orderId = "";
    private int mFrom = -1;
    private ImageView loadingImgv = null;
    private RotateAnimation animation = null;
    private boolean isProcessThread = true;
    private CarpoolOkCancelDialog mCarpoolOkCancelDialog = null;

    /**
     * 通过订单id实现挑起Dialog
     *
     * @param context
     * @param orderId
     */
    public CarPoolReceiptDialog(Activity context, String orderId) {
        super(context);
        mContext = context;
        this.orderId = orderId;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mView = APIProxy.res().inflate(R.layout.carpool_receipt_view);
        setCanceledOnTouchOutside(false);
        setContentView(mView);
        initView();
    }

    /**
     * 如果是来自于订单列表页面，则直接展示已经推送车辆的数量，不在以动画的形式增加
     *
     * @param context
     * @param orderId
     * @param from    -1:动画增加 其他:没有动画
     */

    public CarPoolReceiptDialog(Activity context, String orderId, int from) {
        super(context);
        mContext = context;
        this.orderId = orderId;
        this.mFrom = from;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mView = APIProxy.res().inflate(R.layout.carpool_receipt_view);
        setCanceledOnTouchOutside(false);
        setContentView(mView);
        initView();
    }

    private void initView() {
        mCloseDialog = mView.findViewById(R.id.order_hint_top);
        mCancelOrder = mView.findViewById(R.id.cancle_order_btn);
        mNotifyTimeTv = (TextView) mView.findViewById(R.id.notify_time_tv);
        mNotifyTimeUnitTv = (TextView) mView.findViewById(R.id.notify_time_unit);
        mReceiptNumTv = (TextView) mView.findViewById(R.id.receipt_driver_num);
        mCloseDialog.setOnClickListener(this);
        // mCancelOrder.setOnClickListener(this);

        handler.postDelayed(runnable, 1000);
        loadingImgv = (ImageView) mView.findViewById(R.id.imgv_loading);
        animation = new RotateAnimation(0f, 361f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(1000 * 3);
        animation.setRepeatCount(Animation.INFINITE);
        //loadingImgv.setAnimation(animation);
        loadingImgv.startAnimation(animation);

        mScreenReceiver = new ScreenBroadcastReceiver();
        startScreenBroadcastReceiver();
        mCancelOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_AWAIT_ORDER_PAGE,
                        StatisticsUtil.OFFLINE_ACT_CANCEL_BT);

                mCarpoolOkCancelDialog = CarpoolOkCancelDialog.showDialog(
                        (FragmentActivity) APIProxy.res().getBaseActivity(),
                        "",
                        "是否取消该订单?",
                        "是",
                        "否",
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                cancelOrder();
                            }
                        });
            }
        });
    }

    @Override
    public void show() {
        super.show();
        StatisticsUtil.getInstance().addStatisticsOnline(StatisticsUtil.DA_SRC_VALUE_AWAIT_ORDER_PAGE);
        ColorDrawable dw = new ColorDrawable(android.R.color.transparent);
        getWindow().setBackgroundDrawable(dw);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.dimAmount = 0f;
        getWindow().setWindowAnimations(R.style.curDialogDownToUpAnim);
        int width = APIProxy.sys().getScreenWidth();
        getWindow().setLayout(width, -1);
        AnimationUtilsForCarpool.getInstance().translateBottomToTop(mView);

    }

    @Override
    public void onBackPressed() {
    }

    public void dissmissDialog() {
        loadingImgv.clearAnimation();
        isProcessThread = false;
        handler.removeCallbacks(runnable);
        handler.removeMessages(2);
        carPushHander.removeCallbacks(carNumRunnable);
        updateNumHander.removeMessages(0);
        handlerCountDown.removeCallbacks(DownTimeRunnable);
        handlerCountDown.removeMessages(1);
        stopScreenBroadcastReceiver();
        AnimationUtilsForCarpool.getInstance().translateBottomToTopReverse(mView, new AnimationListenerForCarpool() {
            @Override
            public void onAnimationEnd(Animation animation) {
                dismiss();
            }
        });
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_hint_top:
                dissmissDialog();
                break;
            case R.id.cancle_order_btn:
                break;
            default:
                break;
        }

    }

    private void cancelOrder() {
        OrderCancelData orderCancelData = new OrderCancelData(mContext);
        orderCancelData.setOrderNo(orderId);
        orderCancelData.setCancelReason("");

        orderCancelData.post(new IDataStatusChangedListener<OrderCancelResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderCancelResponse> comNetData,
                                            OrderCancelResponse orderCancelResponse,
                                            int i) {

                if (orderCancelResponse != null && orderCancelResponse.data != null) {
                    if (orderCancelResponse.data.orderStatusId == 13 || orderCancelResponse.data.orderStatusId == 14) {
                        ToastForCarpool.show(mContext, orderCancelResponse.data.orderStatusDesc);
                        if (isShowing()) {
                            dissmissDialog();
                        }

                    }
                } else {
                    ToastForCarpool.show(mContext, "网路异常,请检查网络");
                    if (isShowing()) {
                        dissmissDialog();
                    }
                }

            }
        });

    }

    private void waiteOrders() {
        final OrderDetailData orderDetailData = new OrderDetailData(mContext);
        orderDetailData.setOrderId(this.orderId);
        orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData,
                                            OrderDetailResponse orderDetailResponse,
                                            int i) {
                if (orderDetailResponse != null && orderDetailResponse.data != null) {

                    if (orderDetailResponse.data.orderStatusId == 7 || orderDetailResponse.data.orderStatusId == 13) {
                        //TODO 订单详情-抢单成功
                        if (isShowing()) {
                            dissmissDialog();
                        }
                        if (mCarpoolOkCancelDialog != null && mCarpoolOkCancelDialog.isShowing()) {
                            mCarpoolOkCancelDialog.dismiss();
                        }
                        Bundle b = new Bundle();
                        b.putString("orderId", orderId);
                        APIProxy.navi().navigateTo(OrderDetailPage.class, b);
                        return;
                    } else if (orderDetailResponse.data.orderStatusId == 3 || orderDetailResponse.data.orderStatusId
                            == 1) {
                        //TODO 抢单超时 和发单失败
                        if (isShowing()) {
                            dissmissDialog();
                        }
                        if (mCarpoolOkCancelDialog != null && mCarpoolOkCancelDialog.isShowing()) {
                            mCarpoolOkCancelDialog.dismiss();
                        }
                        Bundle b = new Bundle();
                        b.putString("orderId", orderId);
                        APIProxy.navi().navigateTo(OrderDetailPage.class, b);
                        return;
                    } else {
                        //handler.postDelayed(runnable, 1000);
                    }
                    mCurrentSystem = Long.parseLong(orderDetailResponse.data.currentTime);
                    if (mWaitDisableTime != orderDetailResponse.data.waitDisableTime) {
                        mWaitDisableTime = orderDetailResponse.data.waitDisableTime;
                        mWaitEndTime = Long.parseLong(orderDetailResponse.data.waitEndTime);
                        mWaitDisableTime = orderDetailResponse.data.waitDisableTime;
                        if (mCountDownTime != mWaitEndTime - mCurrentSystem) {
                            mCountDownTime = mWaitEndTime - mCurrentSystem;
                            mNotifyTimeTv.setText((int) mCountDownTime / 60 + "");
                        } else {
                            mNotifyTimeTv.setText((int) mWaitDisableTime / 60 + "");
                        }

                        // loadingImgv.clearAnimation();
                        //  loadingImgv.setVisibility(View.GONE);
                        // mView.findViewById(R.id.text_detail).setVisibility(View.VISIBLE);
                        mView.findViewById(R.id.lin_circle_white).setVisibility(View.VISIBLE);
                        countDownTimer();
                    }

                    /// orderDewtailResponse.data.pushNum = 729;
                    if (mPushNumber != orderDetailResponse.data.pushNum) {
                        carPushHander.removeCallbacks(carNumRunnable);
                        mShowNumber = Integer.parseInt(mReceiptNumTv.getText().toString());
                        mPushNumber = orderDetailResponse.data.pushNum;
                        /**
                         * 区分来源，确定是否随机增加托送车辆数
                         */
                        if (mFrom == -1) {
                            if (mShowNumber < mPushNumber && isProcessThread) {
                                carPushHander.postDelayed(carNumRunnable, 1000);
                            }
                        } else {
                            mReceiptNumTv.setText(mPushNumber + "");
                        }
                    }
                    //  if (isProcessThread) {
                    handler.postDelayed(runnable, 1000);
                    //  }

                } else {
                    dissmissDialog();
                    ToastForCarpool.show(mContext, "网络异常，请稍候再试");
                }
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isProcessThread && msg.what == 2) {
                waiteOrders();
            }

        }
    };

    private Runnable runnable = new Runnable() {

        public void run() {
            if (isProcessThread) {
                handler.sendEmptyMessage(2);
            }
        }
    };

    private Handler updateNumHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                if (isProcessThread) {
                    int temp = (int) (mShowNumber + Math.random() * 10);
                    if (temp <= mPushNumber) {
                        mReceiptNumTv.setText(temp + "");
                        mShowNumber = temp;
                        if (temp == mPushNumber) {
                            carPushHander.removeCallbacks(carNumRunnable);
                        }
                    }
                }

            }

        }
    };

    private Handler carPushHander = new Handler();
    private Runnable carNumRunnable = new Runnable() {

        public void run() {
            if (isProcessThread) {
                updateNumHander.sendEmptyMessage(0);
                carPushHander.postDelayed(this, 1000);
            }
        }
    };

    final Handler handlerCountDown = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (isProcessThread) {
                        int time = (int) (mCountDownTime - 60) / 60;
                        String temp = time + "";
                        mNotifyTimeTv.setText(temp);
                        mCountDownTime = mCountDownTime - 60;
                        if (time > 0) {
                            handlerCountDown.postDelayed(DownTimeRunnable, 1000 * 60);
                        }

                    }

            }

            super.handleMessage(msg);
        }
    };
    /**
     * 倒计时分钟
     */
    private Runnable DownTimeRunnable = new Runnable() {

        public void run() {
            if (isProcessThread) {
                handlerCountDown.sendEmptyMessage(1);
            }
        }
    };

    private void countDownTimer() {

        if (mWaitEndTime - mCurrentSystem <= 0) {
            mNotifyTimeTv.setText("0");
            dissmissDialog();
            Bundle b = new Bundle();
            b.putString("orderId", orderId);
            APIProxy.navi().navigateTo(OrderDetailPage.class, b);
        } else {
            mCountDownTime = mWaitEndTime - mCurrentSystem;
            //可以进行倒计时
            String temp = mCountDownTime / 60 + "";
            mNotifyTimeTv.setText(temp);
            //TODO 开始倒计时
            if (isProcessThread) {
                handlerCountDown.postDelayed(DownTimeRunnable, 1000 * 60);
            }

        }

    }

    /**
     * 广播监听
     */
    private ScreenBroadcastReceiver mScreenReceiver;

    private class ScreenBroadcastReceiver extends BroadcastReceiver {
        private String action = null;

        @Override
        public void onReceive(Context context, Intent intent) {
            action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                // 开屏
                mWaitDisableTime = 0L;
                mPushNumber = 0;
                isProcessThread = true;
                handler.postDelayed(runnable, 1000);
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                // 锁屏
                mWaitDisableTime = 0L;
                mPushNumber = 0;
                isProcessThread = false;
                handler.removeCallbacks(runnable);
                handler.removeMessages(2);
                carPushHander.removeCallbacks(carNumRunnable);
                updateNumHander.removeMessages(0);
                handlerCountDown.removeCallbacks(DownTimeRunnable);
                handlerCountDown.removeMessages(1);
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                // 解锁
              /*  mWaitDisableTime = 0L;
                mPushNumber = 0;
                isProcessThread = true;
                handler.postDelayed(runnable, 1000);*/
            }
        }
    }

    private void startScreenBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        mContext.registerReceiver(mScreenReceiver, filter);

    }

    private void stopScreenBroadcastReceiver() {
        if (mScreenReceiver != null) {

            try {
                mContext.unregisterReceiver(mScreenReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } finally {
                mScreenReceiver = null;
            }

        }

    }

}